package com.sxf.view.datatables;

import java.util.Map;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;

import com.sxf.common.tools.SpringTools;
import com.sxf.mybatis.page.Pagination;

/**
 * DataTables帮助类
 * 
 * @author phsxf01
 * 
 */
public class DatatablesHelp {
	private static final ObjectMapper JACKSON_MAPPER = SpringTools
			.getObjectMapper();

	public static DataTables getDataTable(String dtjson) throws Exception {
		DataTables dt = null;
		Map<String, String> map = null;
		map = JACKSON_MAPPER.readValue(dtjson,
				new TypeReference<Map<String, String>>() {
				});
		if (map != null && !map.isEmpty()) {
			dt = new DataTables();
			dt.setDisplayStart(Integer.parseInt(map.get("iDisplayStart")));
			dt.setDisplayLength(Integer.parseInt(map.get("iDisplayLength")));
			dt.setEcho(Integer.parseInt(map.get("sEcho")));
			dt.setColumns(map.get("sColumns"));
			dt.setSearch(map.get("sSearch"));
			dt.setColumnNum(Integer.parseInt(map.get("iColumns")));
		}
		return dt;
	}

	public static DataTablesReturn getDataTableReturn(Pagination<?> page,
			DataTables dt) {
		DataTablesReturn tableReturn = null;
		if (page != null && dt != null) {
			tableReturn = new DataTablesReturn();
			tableReturn.setsEcho(dt.getEcho());
			tableReturn.setsColumns(dt.getColumns());
			tableReturn.setAaData(page.getRows());
			int total = 0;
			if (page.getRows() != null && !page.getRows().isEmpty()) {
				total = (int) page.getTotal();
			}
			tableReturn.setiTotalDisplayRecords(total);
			tableReturn.setiTotalRecords(total);
		}
		return tableReturn;
	}
}
